﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebRamosUC.Models
{
    public class PaginatedList<T> : List<T>
    {
        public int PageIndex { get; private set; }

        public int PageSize { get; private set; }

        public int TotalCount { get; private set; }

        public int TotalPages { get; private set; }

        //MATIAS
        public List<T> Source { get; private set; }

        public PaginatedList(IQueryable<T> source, int pageIndex, int pageSize)
        {
            //MATIAS
            Source = source.ToList();
            

            PageIndex = pageIndex;
            PageSize = pageSize;
            TotalCount = source.Count();
            TotalPages = (int)Math.Ceiling(TotalCount / (double)PageSize);
            this.AddRange(source.Skip(PageIndex * PageSize).Take(PageSize));
        }

        public bool HasPreviousPage
        {
            get
            {
                return (PageIndex > 0);
            }
        }

        public bool HasNextPage
        {
            get
            {
                return (PageIndex + 1 < TotalPages);
            }
        }

        public int pageFirst(string inicio)
        {
            
            int num = 0;

            // por alguna razon da vuelta el orden
            for (int i = (TotalCount - 1) ; i > -1; i--)
            {
                if (Source[i].ToString().StartsWith(inicio))
                    num = i;
            }

            int page = (int) (num/(double)PageSize);

            return page;
        }

        public int pageFirst(char inicio)
        {

            int num = -1;
            int page = 0;

            // por alguna razon da vuelta el orden
            for (int i = (TotalCount - 1); i > -1; i--)
            {
                if (Source[i].ToString().StartsWith("" + inicio))
                {
                    num = i;
                    page = (int)(num / (double)PageSize);
                }
            }

            
            if(num==-1 && (int)inicio>65)
                page = pageFirst((char)((int)inicio-1));
            
                

            return page;
        }
    }
}